package org.example.novelcrawler.util;

import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Component
public class FileUtil {

    public String ensureOutputDir(String baseDir, String novelName) throws IOException {
        String outputDir = baseDir + File.separator + novelName;
        Files.createDirectories(Paths.get(outputDir));
        return outputDir;
    }

    public void saveChapterToTxt(String outputDir, int chapterIndex, String chapterTitle, String content) throws IOException {
        String fileName = String.format("第%d章 %s.txt", chapterIndex, chapterTitle);
        String filePath = outputDir + File.separator + fileName;

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write("第" + chapterIndex + "章 " + chapterTitle);
            writer.newLine();
            writer.newLine();
            writer.write(content);
            writer.newLine();
        }
    }

    public void saveAllToTxt(String outputDir, String novelName, String content) throws IOException {
        String filePath = outputDir + File.separator + novelName + ".txt";

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(content);
        }
    }
}